function _GetData(table, key) {
    return new Promise((resovle, reject) => {
        let trans = _db.transaction(table, "readonly");
        let objectStore = trans.objectStore(table)
        let _req = objectStore.get(key);
        _req.onsuccess = function () {
            resovle(_req.result);
        };
        _req.onerror = function (event) {
            reject(event);
        };
    });
}

function _SetData(table, key, value) {
    return new Promise((resovle, reject) => {
        let trans = _db.transaction(table, "readwrite");
        let objectStore = trans.objectStore(table)
        let _req = objectStore.put(value, key);
        _req.onsuccess = function () {
            resovle();
        };
        _req.onerror = function (event) {
            reject(event);
        };
    });
}

function _GetData2(table, key) {
    return _Init().then(() => {
        return _GetData(table, key);
    });
}

function _SetData2(table, key, value) {
    return _Init().then(() => {
        return _SetData(table, key, value);
    });
}

function _PromiseReject() {
    return Promise.reject('GlobalDB not ready.');
}

const _DB_NAME = "SLOG";
const _DB_VERSION = 1;
const _DB_ARRTABLE = ['articles', 'article_list'];
let _db = undefined;

function _Init() {
    const _indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    if(_indexedDB) {
        return new Promise((resovle, reject) => {
            let _DBOpenRequest = _indexedDB.open(_DB_NAME, _DB_VERSION);
            _DBOpenRequest.onerror = function (event) {
                console.error('[slog] Error loading database. ', event);
                reject();
            };

            _DBOpenRequest.onsuccess = function (event) {
                _db = event.target.result;
                APIObject.GetData = _GetData;
                APIObject.SetData = _SetData;
                console.log("[slog] GlobalDB ready.");
                resovle();
            };

            _DBOpenRequest.onupgradeneeded = function (event) {
                let _db = event.target.result;
                _DB_ARRTABLE.forEach((v) => {
                    _db.createObjectStore(v);
                })
                console.log("[slog] GlobalDB upgraded.");
            };
        });
    } else return Promise.reject();
}


let APIObject = Object.create({
    GetData: _GetData2,
    SetData: _SetData2,
    DeleteData: _PromiseReject,
    TABLE_ARTICLE: _DB_ARRTABLE[0],
    TABLE_ARTICLE_LIST: _DB_ARRTABLE[1],
});

export default APIObject;
